import { useUser } from "@/hook/useUser/useUser";
import { Alert, Button, Card, message, Tag, Empty, Flex } from "antd";
import { useState, useCallback } from "react";
import { useNavigate } from "react-router-dom";
import {
  SettingOutlined,
  DesktopOutlined,
  PlusCircleOutlined,
  PlusOutlined,
  HolderOutlined,
} from "@ant-design/icons";
import SettingItem from "@/component/SettingItem";
import SectionHeader from "@/component/SectionHeader";
import { USER_CONFIG_OPTIONS } from "./UserHomeData";
import {
  getAllSitesKey,
  getSiteIcon,
  getSiteName,
} from "@/component/Common/commonData";
import SubscribeTags from "@/component/SubscribeTags";

export default function UserHome() {
  const {
    isLoggedIn,
    logout,
    subscribe,
    subscribes,
    openInNewWindow,
    listDisplay,
    updateListDisplay,
    updateOpenInNewWindow,
  } = useUser();
  const navigate = useNavigate();

  const [openInNewWindowState, setOpenInNewWindowState] =
    useState(openInNewWindow);
  const [listDisplayState, setListDisplayState] = useState(listDisplay);
  const [updating, setUpdating] = useState({
    openInNewWindow: false,
    listDisplay: false,
  });
  const [subscribed, setSubscribed] = useState(false);
  const [subscribeItems, setSubscribeItems] = useState(subscribes);
  const [oldSubscribeItems, setOldSubscribeItems] = useState(subscribes);
  const [draggedItemIndex, setDraggedItemIndex] = useState(null);

  // 拖拽处理函数
  // 拖拽开始
  const handleDragStart = useCallback((e, index) => {
    setDraggedItemIndex(index);
    // 设置拖拽效果
    e.dataTransfer.effectAllowed = "move";
    // 为了兼容Firefox，需要设置一些数据
    e.dataTransfer.setData("text/plain", index);
  }, []);

  // 拖拽悬停
  const handleDragOver = useCallback((e, index) => {
    e.preventDefault(); // 允许放置
    if (draggedItemIndex === null) return;

    // 如果拖到自己上面，不做处理
    if (draggedItemIndex === index) return;

    // 交换位置
    const newItems = [...subscribeItems];
    const [draggedItem] = newItems.splice(draggedItemIndex, 1);
    newItems.splice(index, 0, draggedItem);

    // 更新状态和拖拽索引
    setSubscribeItems(newItems);
    setDraggedItemIndex(index);
    setSubscribed(true); // 表示有更改需要保存
  }, [draggedItemIndex,subscribeItems,]);

  // 拖拽结束
  const handleDragEnd = useCallback(() => {
    setDraggedItemIndex(null);
    setSubscribed(true); // 表示有更改需要保存
  }, []);

  // 添加订阅
  const addSubscribe = useCallback(
    (site) => {
      const newItems = [...subscribeItems, site];
      setSubscribeItems(newItems);
      setSubscribed(true); // 表示有更改需要保存
    },
    [subscribeItems]
  );

  // 保存订阅
  const saveSubscribe = useCallback(() => {
    try {
      subscribe(subscribeItems);
      setOldSubscribeItems(subscribeItems); // 更新旧订阅列表
      setSubscribed(false); // 重置订阅状态
      message.success("订阅已保存");
    } catch (error) {
      message.error("保存订阅失败，请稍后再试");
      cancelSave(); // 发生错误时，恢复到旧的订阅列表
    }
  }, [subscribeItems]);

  // 取消订阅
  const cancelSubscribe = useCallback(
    (site) => {
      const newItems = subscribeItems.filter((item) => item !== site);
      setSubscribeItems(newItems);
      setSubscribed(true);
    },
    [subscribeItems]
  );

  // 取消保存
  const cancelSave = useCallback(() => {
    setSubscribeItems(oldSubscribeItems);
    setSubscribed(false);
  }, [oldSubscribeItems]);

  // 跳转到登录页面
  const goToLogin = useCallback(() => {
    navigate("/user/login");
  }, [navigate]);

  // 登出
  const handleLogout = useCallback(() => {
    logout();
    message.success("已注销登录");
  });

  // 更新新窗口打开模式
  const handleUpdateOpenInNewWindow = useCallback(
    async (e) => {
      try {
        const value = e.target.value;
        setOpenInNewWindowState(value);
        setUpdating((prev) => ({ ...prev, openInNewWindow: true }));
        await updateOpenInNewWindow(value);
        message.success("设置已更新");
      } catch (error) {
        message.error("更新新窗口打开模式失败，请稍后再试");
        setOpenInNewWindowState(openInNewWindow);
      } finally {
        setUpdating((prev) => ({ ...prev, openInNewWindow: false }));
      }
    },
    [updateOpenInNewWindow, openInNewWindow]
  );

  // 更新列表展示模式
  const handleUpdateListDisplay = useCallback(
    async (e) => {
      try {
        const value = e.target.value;
        setListDisplayState(value);
        setUpdating((prev) => ({ ...prev, listDisplay: true }));
        await updateListDisplay(value);
        message.success("设置已更新");
      } catch (error) {
        message.error("更新列表展示模式失败，请稍后再试");
        setListDisplayState(listDisplay);
      } finally {
        setUpdating((prev) => ({ ...prev, listDisplay: false }));
      }
    },
    [updateListDisplay, listDisplay]
  );

  return (
    <Card
      title={
        <span style={{ fontSize: "22px", fontWeight: "bold" }}>
          <SettingOutlined style={{ marginRight: "8px" }} />
          用户设置
        </span>
      }
      extra={
        <Button
          type="primary"
          size="small"
          onClick={!isLoggedIn ? goToLogin : handleLogout}
        >
          {!isLoggedIn ? "登录" : "登出"}
        </Button>
      }
      style={{ width: "800px" }}
    >
      {!isLoggedIn && (
        <Alert
          message="未登录，修改将保存在本地，登录后可保存至云端"
          type="warning"
          style={{ marginBottom: "16px" }}
          showIcon
          closable
        />
      )}
      <div style={{ position: "relative" }}>
        <SectionHeader
          icon={<PlusCircleOutlined />}
          title="订阅"
          level={2}
          style={{ marginBottom: "24px" }}
        />
        {subscribed && (
          <span
            style={{
              position: "absolute",
              right: "2px",
              top: "2px",
              display: "flex",
              gap: "8px",
            }}
          >
            <Button
              type="link"
              size="small"
              onClick={cancelSave}
            >
              取消
            </Button>
            <Button
              type="primary"
              size="small"
              onClick={saveSubscribe}
            >
              保存
            </Button>
          </span>
        )}
      </div>

      <SectionHeader
        title="我的订阅"
        level={4}
        style={{ border: "none", margin: "8px 0px" }}
      />
      
      <SubscribeTags
        tags={subscribeItems}
        type="my"
        onRemove={cancelSubscribe}
        draggedItemIndex={draggedItemIndex}
        handleDragStart={handleDragStart}
        handleDragOver={handleDragOver}
        handleDragEnd={handleDragEnd}
      />

      <SectionHeader
        title="全部节点"
        level={4}
        style={{ border: "none", margin: "8px 0px" }}
      />

      <SubscribeTags
        tags={getAllSitesKey().filter((key) => !subscribeItems.includes(key))}
        type="all"
        onAdd={addSubscribe}
      />

      <SectionHeader
        icon={<DesktopOutlined />}
        title="展示"
        level={2}
        style={{ margin: "24px 0px" }}
      />

      <SettingItem
        title={USER_CONFIG_OPTIONS.WINDOW_OPTIONS.title}
        value={openInNewWindowState}
        onChange={handleUpdateOpenInNewWindow}
        options={USER_CONFIG_OPTIONS.WINDOW_OPTIONS.options}
        loading={updating.openInNewWindow}
        style={{ marginBottom: "16px" }}
      />

      <SettingItem
        title={USER_CONFIG_OPTIONS.DISPLAY_OPTIONS.title}
        value={listDisplayState}
        onChange={handleUpdateListDisplay}
        options={USER_CONFIG_OPTIONS.DISPLAY_OPTIONS.options}
        loading={updating.listDisplay}
      />
    </Card>
  );
}
